import register from './../../api/register'

export default {
  // 判断手机号是否存在账号  5分钟内仅验证一次
  validateAccountOfPhone(context, params) {
    return new Promise((resolve, reject) => {
      let state = context.state;
      let phone = params.phone;
      let upv = state.userPhoneValidate;
      // eslint-disable-next-line no-prototype-builtins
      if(upv.hasOwnProperty(phone)) {
        let result = upv[phone];
        let vi = state.validateInterval, timeToDate = new Date() - result.time;
        // 如果是账号已存在，则取未超过保存时间的缓存（防止账号删除）
        if(result.hasAccount && vi > timeToDate) {
          resolve(result);
          return
        }
      }
      // 账号不存在 或者 超过缓存时间的重新获取手机号是否存在账号
      context.dispatch('sendValidateAccountRequest', params).then(result => {
        let setParams = {
          phone: params.phone,
          hasAccount: result.hasAccount,
          time: result.time
        };
        context.commit('setUserPhoneValidate', setParams);
        resolve(result);
      }).catch((e) => {
        reject(e);
      });
    })
  },
  // 发送手机号验证请求
  sendValidateAccountRequest(context, params) {
    return new Promise((resolve, reject) => {
      this.dispatch('request', register.notExistMobile({
          mobile: params.phone
        })).then((res) => {
        let result = {
          hasAccount: !res.result,
          time: new Date().getTime()
        };
        resolve(result)
      }).catch(e => {
        reject(e);
      })
    })
  },
  // 识别营业执照
  distinguishBusinessLicense(context, picId) {
    return new Promise((resolve) => {
      if(!picId) {
        console.error('请传图片id');
        return;
      }
      this.dispatch('request', register.ocrBusinessLicense(picId)).then(res => {
        resolve(res.result);
      })
    })
  },
  // 识别身份信息
  distinguishIdCard(context, picId) {
    return new Promise((resolve) => {
      if(!picId) {
        console.error('请传图片id');
        return;
      }
      this.dispatch('request', register.ocrIdCard(picId)).then(res => {
        resolve(res.result);
      })
    })
  }
}
